package com.xqq.juc;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDebug {

    private static final ReentrantLock lock = new ReentrantLock(true);
    private static int sharedResource = 0;

    public static void main(String[] args) throws InterruptedException {
        // 创建3个竞争线程
        Thread t1 = new Thread(new Worker(), "Worker-1");
        Thread t2 = new Thread(new Worker(), "Worker-2");
        Thread t3 = new Thread(new Worker(), "Worker-3");

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println("最终共享资源值: " + sharedResource);
    }

    static class Worker implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                // 🔴 在此设置断点1：观察锁竞争
                lock.lock();
                try {
                    // 🔴 在此设置断点2：观察锁持有状态
                    System.out.println(Thread.currentThread().getName() + " 获取锁");

                    // 修改共享资源
                    sharedResource++;

                    // 模拟工作
                    Thread.sleep(200);

                    // 锁重入演示
                    if (i == 0) {
                        lock.lock(); // 重入锁
                        try {
                            System.out.println(Thread.currentThread().getName() + " 重入锁");
                            sharedResource += 10;
                            Thread.sleep(100);
                        } finally {
                            lock.unlock(); // 释放重入锁
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    // 🔴 在此设置断点3：观察锁释放
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName() + " 释放锁");
                }
            }
        }
    }
}